<?php
/**
 * Created by PhpStorm.
 * User: u
 * Date: 2019/5/13
 * Time: 18:05
 */

namespace common\logics\testkq;

use Yii;
use common\services\kq\KqPayService;
use common\widgets\Tool;
use yii\base\BaseObject;

class KqLogic extends BaseObject implements IKq
{

    /** @var \common\sources\read\businessrechargerecord\BusinessRechargeRecordAccess $RBusinessRechargeRecordAccess  **/
    private $RBusinessRechargeRecordAccess;
    /** @var \common\sources\write\businessrechargerecord\BusinessRechargeRecordAccess $WBusinessRechargeRecordAccess **/
    private $WBusinessRechargeRecordAccess;
    /** @var \common\sources\read\buyuser\BuyUserAccess $RBuyUserAccess **/
    private $RBuyUserAccess;
    /** @var \common\sources\read\buyuser\BuyUserAcountAccess  $RBuyUserAcountAccess **/
    private $RBuyUserAcountAccess;
    /** @var \common\sources\write\businessacount\BusinessAcountAccess $WBusinessAcountAccess  ***/
    private $WBusinessAcountAccess;
    /** @var \common\sources\write\businessdepositrecord\BusinessDepositRecordAccess $WBusinessDepositRecordAccess **/
    private $WBusinessDepositRecordAccess;
    public function init()
    {
        $this->RBusinessRechargeRecordAccess = Yii::$container->get("RBusinessRechargeRecordAccess");
        $this->WBusinessRechargeRecordAccess = Yii::$container->get("WBusinessRechargeRecordAccess");
        $this->RBuyUserAccess = Yii::$container->get("RBuyUserAccess");
        $this->RBuyUserAcountAccess = Yii::$container->get("RBuyUserAcountAccess");
        $this->WBusinessAcountAccess = Yii::$container->get("WBusinessAcountAccess");
        $this->WBusinessDepositRecordAccess = Yii::$container->get("WBusinessDepositRecordAccess");
        parent::init();
    }

    public function payAmount($data)
    {
        if(empty($data['bus_id'])){
            return Tool::returnJson([],401,"商家用户id不能为空");
        }
        if(empty($data['pay_type'])){
            return Tool::returnJson([],402,"充值方式不能为空");
        }
        if(empty($data['order_amount'])){
            return Tool::returnJson([],403,"充值金额不能为空");
        }
        if(!($data['pay_type'] == 1 || $data['pay_type'] == 2 )){
            return Tool::returnJson([],405,"选择充值方式有误");
        }
        if(empty($data['shop_name']))
        {
            return Tool::returnJson([],406,"商品名称不能为空");
        }

        $kqPayService = new KqPayService();
        $arr = $kqPayService->pay($data);
        if(empty($arr['pay_url'])){
            return Tool::returnJson([],407,"第三方支付异常，请切换其他支付方式");
        }
        //增加充值记录
        return Tool::returnJson($arr,200,"成功");
    }
    //银行卡业务处理
    public function payBank($data)
    {
        if(empty($data['bus_id'])){
            return Tool::returnJson([],401,"商家用户id不能为空");
        }
        if(empty($data['pay_type'])){
            return Tool::returnJson([],402,"充值方式不能为空");
        }
        if(empty($data['order_amount'])){
            return Tool::returnJson([],403,"充值金额不能为空");
        }
        if($data['pay_type'] != 3){
            return Tool::returnJson([],405,"选择充值方式有误");
        }
        if(empty($data['orderId']))
        {
            return Tool::returnJson([],406,"订单编号不能为空");
        }
        if(empty($data['shop_name']))
        {
            return Tool::returnJson([],406,"商品名称不能为空");
        }


        $kqPayService = new KqPayService();
        $arr = $kqPayService->payBank($data);
        return $arr;
    }
    //回调处理
    public function doNotify($data)
    {
        $kqPayService = new KqPayService();
        $result = $kqPayService->doNotify($data);
        $rechar_str = '';
        if($_REQUEST['ext2'] == 1)
        {
            $rechar_str = '快钱-微信';
        }else if($_REQUEST['ext2'] == 2)
        {
            $rechar_str = '快钱-支付宝';
        }else if($_REQUEST['ext2'] == 3)
        {
            $rechar_str = '快钱-网银';
        }

        if($result['rtnOK'] == 1)
        {
            $busRechargeRecord = $this->RBusinessRechargeRecordAccess->getRechargeRecord(['order_id'=>$_REQUEST['orderId']]);
            if(empty($busRechargeRecord))
            {
                //回调成功之后的判断
                $trr = [
                    'bus_id' => $_REQUEST['ext1'],
                    'pay_type'=> 5,
                    'amount' => number_format($_REQUEST['payAmount']/100,2,'.',''),
                    'order_id' => $_REQUEST['orderId'],
                    'pay_status' =>2,
                    'remark' => "充值金额 +".number_format($_REQUEST['payAmount']/100,2,'.',''),
                    "shop_name" => $_REQUEST['ext2']
                ];
                $res = $this->WBusinessRechargeRecordAccess->addRechargeRecord($trr);
                if($res)
                {
                    $user = $this->RBuyUserAccess->getBuyUserInfo($_REQUEST['ext1']);
                    if(!empty($user))
                    {
                        //修改账号余额
                        $userAccount = $this->RBuyUserAcountAccess->getBuyUserAccount($_REQUEST['ext1']);
                        if(!empty($userAccount))
                        {
                            $total_deposit = number_format($userAccount['total_deposit']+$_REQUEST['payAmount']/100,2,".","");
                            $ava_deposit = number_format($userAccount['ava_deposit']+$_REQUEST['payAmount']/100,2,".","");
                            $this->WBusinessAcountAccess->modifyBusAccount(['total_deposit' => $total_deposit,"ava_deposit" => $ava_deposit,"freezing_deposit" => $userAccount['freezing_deposit'],"ava_pepper" => $userAccount['ava_pepper'],"freezing_golds" => $userAccount['freezing_golds'],"bus_id"=>$_REQUEST['ext1']]);
                        }else
                        {
                            $total_deposit = number_format($_REQUEST['payAmount']/100,2,".","");
                            $ava_deposit = number_format($_REQUEST['payAmount']/100,2,".","");
                            $this->WBusinessAcountAccess->addAccount(['bus_id' => $_REQUEST['ext1'],'total_deposit' => $total_deposit,"ava_deposit" => $ava_deposit]);
                        }
                        $balance = number_format($userAccount['ava_deposit'] + $_REQUEST['payAmount']/100,2,".","");
                        //添加充值记录
                        $frr = [
                            'bus_id' => $_REQUEST['ext1'],
                            'income' => number_format($_REQUEST['payAmount']/100,2,'.',''),
                            'expend' => '0',
                            'balance' => $balance,
                            'fund_type' => 1,
                            'tran_num' => $_REQUEST['orderId'],
                            'type' => 1,
                            'desc' => $rechar_str,
                            'is_back' => 1,
                            'remark' => '商家账号充值',
                            'operator' => "system",
                        ];
                        $this->WBusinessDepositRecordAccess->addDepositRecord($frr);
                        // 首次充值交易提醒
                        $dd_url = Yii::$app->params['dd_kq_pay_recharge'];
                        $message = $user['phone']."充值". number_format($_REQUEST['payAmount']/100,2,'.','')."元，交易编号".$_REQUEST['orderId'];
                        $param = array ('msgtype' => 'text','text' => array ('content' => $message),"at"=>["isAtAll" =>true]);
                        $data_string = json_encode($param);
                        $this->request_by_curl($dd_url, $data_string);
                    }

                }
            }

        }
        return $result['str'];
    }

    //检查是否支付成功
    public function checktOrderStatus($data)
    {
        if(empty($data['bus_id'])){
            return Tool::returnJson([],401,"商家用户id不能为空");
        }
        if(empty($data['orderId']))
        {
            return Tool::returnJson([],402,"商户订单编号不能为空");
        }
        if(empty($data['safetyCode']))
        {
            return Tool::returnJson([],403,"安全码不能为空");
        }
        if($data['safetyCode'] != md5($data['bus_id'].$data['orderId']))
        {
            return Tool::returnJson([],405,"安全码不正确");
        }
        //判断用户是否存在
        $user = $this->RBuyUserAccess->getBuyUserInfo($data['bus_id']);
        if(empty($user))
        {
            return Tool::returnJson([],5150,"用户不存在");
        }
        $rechargerecord = $this->RBusinessRechargeRecordAccess->getRechargeRecord(["order_id" => $data['orderId']]);
        if(empty($rechargerecord))
        {
            return Tool::returnJson([],405,"暂未找到对应的商户");
        }
        return Tool::returnJson($rechargerecord,200,"成功");
    }

    private function request_by_curl($remote_server, $post_string)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $remote_server);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array ('Content-Type: application/json;charset=utf-8'));
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_string);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        // 线下环境不用开启curl证书验证, 未调通情况可尝试添加该代码
        curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0);
        $data = curl_exec($ch);
        curl_close($ch);

        return $data;
    }

}